﻿using System;
using System.Management.Automation.Runspaces;
using BGShell.PowerShell.Commands;

namespace BGShell.PowerShell.Runspaces
{
    internal static class DefaultProfile
    {
        private const string PromptFunction = @"
if ($Global:Host.PrivateData.IsBackground)
{
    $Global:Host.UI.RawUI.WindowTitle = ""Background Runspace""
}
else
{
    $Global:Host.UI.RawUI.WindowTitle = (Microsoft.PowerShell.Management\Get-Location).Path
}

""$(if ($Global:NestedPromptLevel) 
  {
      Microsoft.PowerShell.Utility\New-Object string ([char]0xB7), $Global:NestedPromptLevel
  })[$((Microsoft.PowerShell.Core\Get-History -Count 1).Id + 1)] $([char]0xBB) """;

        private const string TabExpansionFunction = @"
param($line, $lastWord)
Get-BGShellTabExpansion $line $lastWord
";

        private const string ClearHostFunction = @"
$Host.PrivateData.ClearScreen()
";

        public static InitialSessionState CreateSessionState()
        {
            var session = InitialSessionState.CreateDefault();

            AddCmdlet(session, "Get-BGShellTabExpansion", typeof(GetTabExpansionCommand));
            AddCmdlet(session, "Start-BGShellTabExpansion", typeof(StartTabExpansionCommand));

            AddFunction(session, "Prompt", PromptFunction);
            AddFunction(session, "Clear-Host", ClearHostFunction);
            AddFunction(session, "TabExpansion", TabExpansionFunction);

            return session;
        }

        public static Command[] GetInitializationPipelines()
        {
            return new Command[]
            {
                new Command("Start-BGShellTabExpansion"),
            };
        }

        private static void AddCmdlet(InitialSessionState session, String name, Type implementation)
        {
            session.Commands.Add(new SessionStateCmdletEntry(name, implementation, null));
        }

        private static void AddFunction(InitialSessionState session, String name, String definition)
        {
            session.Commands.Add(new SessionStateFunctionEntry(name, definition));
        }
    }
}
